<?php
class View {
	private $vars = array();
  	private $viewFile;
  	private $layoutFile;
  	private $title;
  	private $flag;
  	private $scripts;
  	private $metaTitle;
  	private $metaDesc;
  	private $metaKeys;
  	private $config;

  	function __construct(){
    	$this->config = Config::singleton();
    	$this->title = $this->config->get('title');
    	$this->flag = $this->config->get('flag');
    	$this->scripts = $this->config->get('scripts');
    	$this->meta_title = $this->config->get('meta_title');
    	$this->meta_desc = $this->config->get('meta_desc');
    	$this->meta_keys = $this->config->get('meta_keys');
  	}

	public function show($view, $layout, $vars = array()) {
  		if(file_exists($this->config->get('views_path').$view.'.php')){
      		$this->viewFile =  $this->config->get('views_path').$view.'.php';
  		}
  		else{
  	  		throw new Exception('Error: El archivo de la vista invocada no existe');
  		}
		if(file_exists($this->config->get('layouts_path').$layout.'.php')){
      		$this->layoutFile =  $this->config->get('layouts_path').$layout.'.php';
  		}
  		else{
  	  		throw new Exception('Error: El archivo del layout invocado no existe');
  		}
    	$this->vars = $vars;
    	if(isset($this->vars['title'])){$this->title = $this->vars['title'];}
    	if(isset($this->vars['flag'])){$this->flag = $this->vars['flag'];}
    	if(isset($this->vars['scripts'])){$this->scripts = $this->vars['scripts'];}
    	if(isset($this->vars['meta_title'])){$this->metaTitle = $this->vars['meta_title'];}
    	if(isset($this->vars['meta_desc'])){$this->metaDesc = $this->vars['meta_desc'];}
    	if(isset($this->vars['meta_keys'])){$this->metaKeys = $this->vars['meta_keys'];}
    	try{
      		$this->includeLayout();
    	}
    	catch(Exception $e){
      		throw $e;
    	}
  	}

	private function includeElement($element) {
    	$element_file =  $this->config->get('elements_path').$element.".php";
    	try{
      		if(file_exists($element_file)){
        		include($element_file);
      		}
    	}
    	catch(Exception $e) {
      		throw $e;
    	}
  	}

  	private function includeView() {
    	try{
      		if(file_exists($this->viewFile)){
        		include($this->viewFile);
      		}
      	else{
        	throw new exception("La vista ".$this->viewFile." no existe");
      		}
    	}
    	catch(Exception $e) {
      		throw $e;
    	}
  	}

  	private function includeLayout() {
    	try{
      		if(file_exists($this->layoutFile)){
        		include($this->layoutFile);
      		}
      		else{
        		throw new exception("La plantilla ".$this->layoutFile." no existe");
      		}
    	}
    	catch(Exception $e) {
      		throw $e;
    	}
  	}

}
/*
 Uso:
 $objView = new View();
 $objView->show('vista', 'layout', $vars);
*/
?>
